package com.agent.commons.utils;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * RabbitMq消息队列相关工具类
 */
@Slf4j
@Component
public class RabbitMqUtil {

    private static RabbitTemplate rabbitTemplate;

    @Autowired
    public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
        RabbitMqUtil.rabbitTemplate = rabbitTemplate;
    }


    /**
     * 生成者confirm机制设置
     * @return
     */
    public static CorrelationData  getCorrelationData() {
        CorrelationData cd = new CorrelationData(UUID.randomUUID().toString());
        // 使用 CompletableFuture 的 whenComplete 替代 addCallback
        cd.getFuture().whenComplete((result, throwable) -> {
            if (throwable != null) {
                log.error("spring amqp 处理确认结果异常", throwable);
            } else {
                if (result.isAck()) {
                    log.info("收到ConfirmCallback ack,消息发送成功");
                } else {
                    log.error("收到ConfirmCallback nack,消息发送失败！reason: {}", result.getReason());
                }
            }
        });
        return cd;
    }

    /**
     * 发送消息到交换机(direct)
     * @param exchange
     * @param message
     * @param routingKey
     */
    public static void sendMessageDirect(String exchange, Object message, String routingKey){
        rabbitTemplate.convertAndSend(exchange, routingKey, message, getCorrelationData());
    }

    /**
     * 发送消息到交换机(fanout)
     */
    public static void sendMessageFanout(String exchange, Object message){
        rabbitTemplate.convertAndSend(exchange, "", message, getCorrelationData());
    }

}
